/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cmd.biz;

import cn.easyplatform.studio.StudioException;
import cn.easyplatform.studio.dao.DaoException;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.FieldVo;

import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class BatchUpdateCmd implements Command<Integer> {

	private String dbId;

	private String sql;

	private List<List<FieldVo>> params;

	/**
	 * @param dbId
	 * @param sql
	 * @param params
	 */
	public BatchUpdateCmd(String dbId, String sql, List<List<FieldVo>> params) {
		this.dbId = dbId;
		this.sql = sql;
		this.params = params;
	}

	/**
	 * @param sql
	 * @param params
	 */
	public BatchUpdateCmd(String sql, List<List<FieldVo>> params) {
		this.sql = sql;
		this.params = params;
	}

	@Override
	public Integer execute(CommandContext cc) {
		try {
			int count = 0;
			cc.beginTx();
			for (List<FieldVo> avgs : params) {
				count += cc.getBizDao(dbId).update(sql, avgs);
			}
			cc.commitTx();
			return count;
		} catch (Exception ex) {
			cc.rollbackTx();
			if (ex instanceof DaoException)
				throw (DaoException) ex;
			throw new StudioException("BatchUpdateCmd:" + ex.getMessage());
		} finally {
			cc.closeTx();
		}
	}

}
